package com.mrjy.maintain.bo;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.mrjy.common.dto.ProgramPromoteInfoDTO;
import com.mrjy.common.entity.ProgramPromoteInfo;
import com.mrjy.common.entity.UserInfo;
import com.mrjy.common.util.ConstantsUtil;
import com.mrjy.common.util.GlobalConstant;
import com.mrjy.common.util.ResultUtil;
import com.mrjy.maintain.dao.IProgramPromoteInfoDao;

@Service
public class ProgramPromoteInfoBo implements IProgramPromoteInfoBo {
	
	@Autowired
	private IProgramPromoteInfoDao programPromoteInfoDao;
	
	@Override
	public Object queryPage(Integer page, Integer rows,
			Integer programId, String programType,HttpSession session) {
		//获取当前登录用户 
		UserInfo loginUser = (UserInfo) session.getAttribute(GlobalConstant.USER_INFO);
		Integer paymentTypeId = null;
		//判断并设置paymentTypeId
		if (ConstantsUtil.getProperty("PROGRAM_PROMOTE_TYPE.COURSEPACKAGE").equals(programType)) {
			paymentTypeId = Integer.parseInt(ConstantsUtil.getProperty("PAYMENT_TYPE.COURSEPACKAGE"));
		}else if (ConstantsUtil.getProperty("PROGRAM_PROMOTE_TYPE.VIDEO").equals(programType)) {
			paymentTypeId = Integer.parseInt(ConstantsUtil.getProperty("PAYMENT_TYPE.VIDEO"));
		}else if (ConstantsUtil.getProperty("PROGRAM_PROMOTE_TYPE.ACTIVITY").equals(programType)) {
			paymentTypeId = Integer.parseInt(ConstantsUtil.getProperty("PAYMENT_TYPE.ACTIVITY"));
		}
		PageHelper.startPage(page, rows);
		List<ProgramPromoteInfoDTO> result = programPromoteInfoDao.queryPageByProgramId(programId, programType, paymentTypeId);
		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("list", result);
		//封装结果集
		for (ProgramPromoteInfoDTO programPromoteInfoDTO : result) {
			if (loginUser!=null) {
				if (loginUser.getId().equals(programPromoteInfoDTO.getUserId())) {
					//列表第一条 展示自己的结果和排名
					resultMap.put("mine", programPromoteInfoDTO);
				}
			}
		}
		
		return ResultUtil.success(resultMap);
	}

	@Override
	public Object txInsert(Integer programId, String programType,HttpSession session) {
		UserInfo loginUser = (UserInfo) session.getAttribute(GlobalConstant.USER_INFO);
		if (null!=loginUser) {
			
			ProgramPromoteInfo info = new ProgramPromoteInfo();
			info.setUserId(loginUser.getId());
			info.setProgramId(programId);
			info.setProgramType(programType);
			if(null != programPromoteInfoDao.queryExist(info)){
				return ResultUtil.success();
			}else{
				programPromoteInfoDao.insertSelective(info);
			}
		}
		return ResultUtil.success();
	}
	
}
